<template>
  <div class="publishMain" v-if="user.postsType == 'pet'">
    <van-form @submit="posts">
      <div class="publish">
        <van-button type="success" round class="btn" native-type="submit">发布</van-button>
      </div>
      <div class="textContent">
        <van-cell-group inset>
          <van-field v-model="message" :rules="[{ required: true, message: '请填写描述' }]" rows="5" required autosize
            label="描述" type="textarea" maxlength="100" placeholder="请输入宠物描述" show-word-limit />
        </van-cell-group>
      </div>
      <div class="upload">
        <van-uploader multiple :rules="[{ required: true, message: '请上传照片' }]" v-model="fileList"
          :before-read="beforeRead" :max-count="9" />
      </div>

      <div class="typeBody">
        <div class="typelist">
          <div class="type" v-for="(item, index) in iconList" :key="index" data-id="index"
            :class="active == index ? 'active' : ''" @click="changeType(index, item.name)">
            <span class="typeIcon">
              <svg class="icon" aria-hidden="true">
                <use :xlink:href="item.icon"></use>
              </svg>
            </span>
            <span class="typeName">{{ item.name }}</span>
          </div>
        </div>
      </div>
      <div class="price">
        <van-field v-model="name" :rules="[{ required: true, message: '请输入名称' }]" required label="名称"
          placeholder="请输入名称" />
        <van-field v-model="age" type="number" max :rules="[{ required: true, message: '请输入年龄' }]" required label="年龄"
          placeholder="请输入年龄" />
      </div>
      <div class="unit">
        <van-field v-model="fieldValue" is-link required readonly :rules="[{ required: true, message: '请选择性别' }]"
          label="性别" placeholder="选择性别" @click="showPicker = true" />
        <van-popup v-model:show="showPicker" round position="bottom">
          <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
        </van-popup>
      </div>
    </van-form>
  </div>
  <div class="publishMain" v-else>
    <van-form @submit="posts">
      <div class="publish">
        <van-button type="success" round class="btn" native-type="submit">发布</van-button>
      </div>
      <div class="titleContent">
        <div class="title">
          <van-field v-model="name" :rules="[{ required: true, message: '请输入标题' }]" required label="标题"
            placeholder="请输入标题" />
        </div>
      </div>

      <div class="upload notpet">
        <van-uploader multiple :rules="[{ required: true, message: '请上传照片' }]" v-model="fileList"
          :before-read="beforeRead" :max-count="9" />
      </div>
      <div class="textContent">
        <van-cell-group inset>
          <van-field v-model="message" :rules="[{ required: true, message: '请填写正文' }]" rows="5" required autosize
            label="正文" type="textarea" maxlength="500" placeholder="请输入正文" show-word-limit />
        </van-cell-group>
      </div>
    </van-form>
  </div>
</template>

<script lang='ts' setup>
import { ref } from 'vue';
import { showFailToast, showToast } from 'vant';
import { publishType } from '@/model/index';
import * as qiniu from 'qiniu-js';
import { getToken, publish } from '@/api/index';
import { Ref } from 'vue';
import { userStore } from '@/store';
import router from '@/router';
const user = userStore()

const iconList = [
  {
    icon: '#icon-btn_badminton',
    name: '猫咪'
  },
  {
    icon: '#icon-che',
    name: '狗狗'
  },
  {
    icon: '#icon-fangzi',
    name: '小猪'
  },
  {
    icon: '#icon-dianqi',
    name: '兔子'
  },
  {
    icon: '#icon-dianzishebei',
    name: '其他'
  }
]
let active: Ref<number> = ref(0)
let message = ref('');
let name = ref('');
let age = ref('');
const fileList = ref([]);
let ImgList: Array<string> = [];
let postType: string = '猫咪'

const posts = async () => {
    const config = {
      region: qiniu.region.z2,
      domain: 'http://sdcpe1fnv.hd-bkt.clouddn.com'
    }
    await getToken().then((res: any) => {
      fileList.value.forEach((file: any) => {
        const observable = qiniu.upload(file.file, null, res.upToken)
        const observer = {
          complete(res: { hash: string; }) {
            const ImgUrl: string = config.domain + '/' + res.hash;
            ImgList.push(ImgUrl)
          }
        }
        observable.subscribe(observer)
      })
    })
    if (ImgList.length == 0&&user.postsType=='pet') {
    showToast('请上传图片！')
    return
  }
    const data: publishType = {
      ImgList: ImgList,
      name: name.value,
      remark: message.value,
      type: postType,
      age: parseInt(age.value),
      gender: fieldValue.value == '公' ? 'male' : 'female',
      postsType: user.postsType
    }
    const sharedata: any = {
      ImgList: ImgList,
      name: name.value,
      remark: message.value,
      postsType: user.postsType
    }
    setTimeout(async () => {
      let params=user.postsType == 'pet'?data:sharedata
      await publish(params).then((res: any) => {
        if (res.code == 200) {
          fileList.value = []
          message.value = ''
          active.value = 0
          name.value = ''
          age.value = ''
          fieldValue.value = ''
          ImgList = []
          userStore().cardList.length == 0
          let route=user.postsType=='pet'?'/index':'/concernInfo'
          router.push(route)
        }
      })
    }, 1500)
  }


const beforeRead = (file: File | Array<File>) => {
  if (file instanceof Array) {
    file.forEach((item) => {
      checkFile(item)
    })
  } else {
    checkFile(file)
  }
  return true
}
const checkFile = (file: File) => {
  const format = ['png', 'jpg', 'jpeg']
  const index = file.name.lastIndexOf(".");
  const finalName = file.name.substring(index + 1);
  if (!format.includes(finalName.toLowerCase())) {
    showFailToast("请上传" + format.join(",") + "格式图片");
    return false;
  }
}

const changeType = (index: number, type: string) => {
  postType = type
  active.value = index
}

const columns = [
  { text: '公', value: '公' },
  { text: '母', value: '母' },
];

const fieldValue = ref('');
const showPicker = ref(false);
//@ts-ignore
const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false;
  fieldValue.value = selectedOptions[0].value
};
</script>

<style lang='less' scoped>
@import url('../common/global.less');


.publishMain {
  gap: 0.625rem;
  .list();
  height: 100%;

  .publish {
    overflow: hidden;
    padding: 0.625rem;

    .btn {
      width: 4.375rem;
      height: 2.25rem;
      float: right;
    }
  }


  .textContent {
    width: 100%;
    margin-bottom: 0.625rem;
  }

  .upload {
    width: 92%;
    background: #fff;
    padding-left: 10px;
    padding-top: 10px;
    margin: 0 auto;
    border-radius: 5px;
    box-sizing: border-box;
  }


  .typeBody {
    width: 92%;
    height: 4.5rem;
    margin: 1rem auto;
    border-radius: 5px;
    background: #fff;

    .typelist {
      display: flex;
      justify-content: center;
      align-items: center;

      .type {
        width: 4rem;
        height: 4rem;
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-align: center;
      }
    }
  }

  .active {
    border-radius: 50%;
    background-color: rgb(86, 87, 86);
    color: #fff;
  }

  .price .unit {
    border-radius: 5px;
    margin: 10px auto;
    width: 85%;
  }
}

.titleContent {
  display: flex;
  justify-content: center;

  .title {
    width: 90%;
    text-align: center;
    margin-bottom: 1rem;
    border-radius: 0.2rem;
  }
}

.upload.notpet {
  margin-bottom: 0.625rem;
}
</style>
